console.log("Scan Tables!")
let colors = ['#04ACF4', '#3CFCCC', '#C61BF0', '#04844C', '#FC5C04', '#F4044C'];
let colorIndex = 0;
let cImage = cLink = cInput = notNull = false;
let separator;

function scanTables() {
    let tables = $("table");
    for (let i = 0; i< tables.length; i++) {
        let table_id = ['TABLE-ID', Math.floor(Math.random().toFixed(5) * 10000), Math.floor(Math.random().toFixed(5) * 10000)].join("-");
        tables[i].setAttribute('table_id', table_id);
    
        let tableSrc = "data:application/csv," + encodeURIComponent(getTableText(tables[i]));
    
        let color = colors[colorIndex++ % colors.length];
        tables[i].style.border = '2px solid ' + color;
    
        let button = document.createElement("a");
        button.dataset.table_id = table_id;
        button.innerText = "导出 CSV文件";
        button.classList.add("btn");
        button.style.margin = "5px 5px 5px 0px";
        button.style.backgroundColor = color;
    
        button.setAttribute("href", tableSrc)
        button.setAttribute("download", table_id + ".csv");
    
        $(tables[i]).before(button)
    }
}

// 接受message
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
	if(request.cmd == 'content' && request.action == 'scanTables') {
        cImage = request.image;
        cLink = request.link;
        cInput = request.input;
        notNull = request.notNull;
        separator = request.separator || "|";
        scanTables();
        sendResponse('SUCCESS');
    }
});


function getTableText(table) {
    let rows = [];
    table.querySelector("thead").querySelectorAll("tr").forEach(function(tr) {
        let ths = tr.querySelectorAll("th");
        let row = [];

        ths.forEach(function(th) {
            row.push(getCSVText(th.innerText));
        });

        rows.push(row);
    });
    

    table.querySelector("tbody").querySelectorAll("tr").forEach(function(tr) {
        let tds = tr.querySelectorAll("td");
        let row = [];

        tds.forEach(function(td) {
            let innerText = td.innerText;
            if (cImage) {
                let imgs = td.querySelectorAll("img");
                if (!notNull || imgs.length > 0) {
                    innerText += separator;
                }
                imgs.forEach(function(element) {
                    innerText += element.src + " ";
                })
            }

            if (cLink) {
                let link = td.querySelectorAll("a");
                if (!notNull || link.length > 0) {
                    innerText += separator;
                }
                link.forEach(function(element) {
                    innerText += element.href + " ";
                })
            }

            if (cInput) {
                let input = td.querySelectorAll("input");
                if (!notNull || input.length > 0) {
                    innerText += separator;
                }
                input.forEach(function(element) {
                    innerText += element.value + " ";
                })

            }
            row.push(getCSVText(innerText));
        });

        rows.push(row);
    });

    return rows.join("\r\n");
}

function getCSVText(str) {
    return '"' + str + '"';
}